import { _decorator, Component, Node, Widget, Label, Button, math, EventHandler, sys, director } from 'cc';
import { createUILabel, createUINode, destroyNode, showToast } from '../utils';
import DataManager from '../Runtime/DataManager';
import { ControllerManager } from '../UI/ControllerManager';
import { HomeElement } from '../UI/HomeElement';
import { AudioMgr } from "../Runtime/AudioMgr"
import { GAME_MODE_ENUM, SOCKET_TYPE } from '../../Enums';
import { userStore } from '../service/user';
import { useSocket } from "../service/socket"
import { getLevels, roomAdd, roomChangeReady, dissolve, join, leave, changeLevel, info } from '../api/game';
import { roomInfo } from '../types/type';
import EventManager from '../Runtime/EventManager';
import { CommonElement } from '../UI/CommonElement';
import { phone } from '../api/user';
import { AdManager } from '../UI/AdManager';
const { ccclass } = _decorator;
const wx = window['wx']
const socket = useSocket();
@ccclass('homeManager')
export class homeManager extends Component {
    private controllerManager
    homeElement: HomeElement
    play_music: boolean = false
    close_node: Node
    easterEgg: Node
    level_list = []
    loadingLevels: Boolean = false
    loadingRoom: Boolean = false
    level_id: number = -1
    room_number: Array<string> = [] //输入的房间号
    level_content: Node
    room_content: Node
    commonElement
    adManager
    async start() {
        // this.level_list = Levels
        const node = createUINode("homeNode")
        node.setParent(this.node)
        this.controllerManager = node.addComponent(ControllerManager)
        this.controllerManager.init()
        this.commonElement = node.addComponent(CommonElement)
        await this.controllerManager.loadAssortAssets()
        if (DataManager.Instance.audioMgr == null) {
            DataManager.Instance.audioMgr = new AudioMgr()
        }
        if (!DataManager.Instance.mute) {
            DataManager.Instance.audioMgr.play(DataManager.Instance.audio.find(item => item.name == '1258_menu_music'))
            this.play_music = true
        }
        // 屏幕初始信息
        const homeElement = node.addComponent(HomeElement)
        homeElement.init(this.play_music)
        this.homeElement = homeElement
        const adManager = node.addComponent(AdManager)
        adManager.init()
        this.adManager = adManager
        userStore().share()
        EventManager.Instance.on("msg", this.websocketMessage, this)
        if (userStore().info?.id) {
            socket.connect()
            if (DataManager.Instance.shareNumber) {
                this.joinGames(DataManager.Instance.shareNumber)
                DataManager.Instance.shareNumber = ""
            }
            // DataManager.Instance.room = {
            //     id: 2,
            //     roomNumber: "857227",
            //     ownerReady: 1,
            //     memberReady: 1,
            //     status: 0,
            //     memberNickname: "ceshi1",
            //     ownerId: "9",
            //     ownerNickname: "ceshi2",
            //     memberId: "10",
            //     is_owner: userStore().info.id == '9'
            // }
            // DataManager.Instance.gameMode = GAME_MODE_ENUM.ONLINE
            // director.loadScene('game')

            setTimeout(async () => {
                if (!DataManager.Instance.room) return
                if (userStore().info.id == DataManager.Instance.room?.ownerId) {
                    console.log(DataManager.Instance.room)
                    await this.getRoomInfo()
                    this.loadRoom(DataManager.Instance.room)
                    DataManager.Instance.room.memberId = null
                } else {
                    this.joinGames(DataManager.Instance.room.roomNumber)
                }
            }, 50)
        }
    }
    onDestroy() {
        EventManager.Instance.off("msg", this.websocketMessage)
        DataManager.Instance.drawerNumber = 0
        DataManager.Instance.audioMgr.stop()
    }
    // 监听socket消息
    async websocketMessage(data) {
        if (DataManager.Instance.room == null) return
        if (data.content.roomId != DataManager.Instance.room.id) return
        // 加入房间
        if (data.type == SOCKET_TYPE.JOINROOM) {
            let empty = this.room_content.getChildByName("memberEmpty")
            empty.active = false
            this.homeElement.createHomemember(this.room_content, data.content)
            // 获取房间信息
            this.getRoomInfo()
        }
        // 离开房间
        if (data.type == SOCKET_TYPE.LEVELROOM) {
            let empty = this.room_content.getChildByName("memberEmpty")
            empty.active = true
            let member = this.room_content.getChildByName("homemember")
            let label = member.getChildByName('user_node').getChildByName('nickName').getComponent(Label)
            destroyNode(member)
            showToast(`${label.string}离开了房间`)
            // 获取房间信息
            this.getRoomInfo()
        }
        // 解散房间 超时未开始解散房间
        if (data.type == SOCKET_TYPE.DISSOLVEROOM || data.type == SOCKET_TYPE.CLEAR) {
            // 关闭弹框
            this.closeElement()
            DataManager.Instance.room = null
            showToast("房间已解散")
        }
        // 修改准备状态
        if (data.type == SOCKET_TYPE.CHANGEREADY) {
            let label
            if (data.content.type == 0) {
                let homeowner = this.room_content.getChildByName("homeowner")
                label = homeowner.getChildByName('plan_Node').getComponent(Label)
            } else if (data.content.type == 1) {
                let homemember = this.room_content.getChildByName("homemember")
                label = homemember.getChildByName('plan_Node').getComponent(Label)
            }
            this.setRoomState(label, data.content)
        }
        // 关卡选择
        if (data.type == SOCKET_TYPE.SELECTLEVEL) {
            let { content, maskBox } = await this.controllerManager.showDrawerContent({ name: 'selectLevel', tips: "关卡选择", showCancle: false })
            this.level_content = content
            this.commonElement.createdLevelChange("homeManager", content, data.content.list, DataManager.Instance.room, maskBox,)
            this.level_list = data.content.list
        }
        // 选择关卡
        if (data.type == SOCKET_TYPE.CHANGELEVEL) {
            this.avenueLevels(null, data.content.level_id, false)
        }
        // 开始游戏
        if (data.type == SOCKET_TYPE.STARTGAME) {
            let { roomId, ...levelInfo } = data.content
            DataManager.Instance.levelInfo = levelInfo
            console.log(data.content, " data.content")
            DataManager.Instance.levelInfo.levels = JSON.parse(levelInfo.levels)
            DataManager.Instance.gameMode = GAME_MODE_ENUM.ONLINE
            director.loadScene('game')
        }
    }
    // 登录游戏
    loginGame() {
        phone({ phone: "15847380321", smsCode: "123456" }).then(res => {
            userStore().setToken(res);
            userStore().get()
            this.homeElement.setActionList()
            socket.connect()
            showToast("登录成功")
            // DataManager.Instance.room = {
            //     id: 2,
            //     roomNumber: "857227",
            //     ownerReady: 1,
            //     memberReady: 1,
            //     status: 0,
            //     memberNickname: "ceshi1",
            //     ownerId: "9",
            //     ownerNickname: "ceshi2",
            //     memberId: "10",
            //     is_owner: true
            // }
            // DataManager.Instance.gameMode = GAME_MODE_ENUM.ONLINE
            // director.loadScene('game')
        }).catch(err => {
            showToast(err.message)
        })
    }
    loginGame1() {
        phone({ phone: "15800000000", smsCode: "123456" }).then(res => {
            userStore().setToken(res);
            this.homeElement.setActionList()
            userStore().get()
            socket.connect()
            // DataManager.Instance.room = {
            //     id: 2,
            //     roomNumber: "857227",
            //     ownerReady: 1,
            //     memberReady: 1,
            //     status: 0,
            //     memberNickname: "ceshi1",
            //     ownerId: "9",
            //     ownerNickname: "ceshi2",
            //     memberId: "10",
            //     is_owner: false
            // }
            // DataManager.Instance.gameMode = GAME_MODE_ENUM.ONLINE
            // director.loadScene('game')
        }).catch(err => {
            showToast(err.message)
        })
    }
    // 创建加入房间的弹框
    async showJoinContent() {
        let { content, maskBox } = await this.controllerManager.showDrawerContent({ name: 'joinGame', tips: "加入房间", showCancle: false })
        const revertNode = createUINode("revertNode")
        revertNode.setParent(maskBox)
        const button = revertNode.addComponent(Button)
        const clickEventHandler = new ControllerManager.EventHandler();
        clickEventHandler.target = this.node; // 这个 node 节点是你的事件处理代码组件所属的节点
        clickEventHandler.component = 'homeManager';// 这个是脚本类名
        clickEventHandler.handler = 'closeJoin';
        clickEventHandler.customEventData = 'joinGame';
        button.duration = .1
        button.zoomScale = 0.95
        button.transition = Button.Transition.SCALE
        button.clickEvents.push(clickEventHandler)
        createUILabel({ parentNode: revertNode, text: "返回" })
        const revertWidget = revertNode.addComponent(Widget)
        revertWidget.isAlignBottom = true
        revertWidget.bottom = 30
        revertWidget.isAlignHorizontalCenter = true
        this.homeElement.createKeyboard(content)
    }
    //点击选择的房间号 
    selectNumber(event: EventHandler, eventData: string) {
        if (eventData == "加 入") {
            this.joinGame()
            return
        }
        if (eventData == "删 除") {
            this.room_number.splice(this.room_number.length - 1, 1)
        } else {
            if (this.room_number.length < 6) {
                this.room_number.push(eventData)
            }
        }
        let value = event.target.parent.parent.getChildByName("value")
        let label = value.getComponent(Label)
        let text = []
        for (let i = 0; i < 6 - this.room_number.length; i++) {
            text.push("*")
        }
        label.string = this.room_number.join("") + text.join("")
    }
    // 创建房间
    async onLineGame() {
        let ad = await this.adManager.playAd()
        if (!ad) return
        if (DataManager.Instance.drawerNumber != 0) {
            return
        }
        this.loadingRoom = true
        roomAdd({}).then((res: roomInfo) => {
            this.loadingRoom = false
            // console.log(res)
            // DataManager.Instance.room = res
            this.loadRoom(res)
        }).catch(err => {
            console.log(err)
            showToast(err.message)
            this.loadingRoom = false
        })
    }
    async getRoomInfo() {
        return info(DataManager.Instance.room.id).then(res => {
            console.log(res, "res")
            DataManager.Instance.room = res
            return res
        }).catch(err => {
            showToast(err.message)
        })
    }
    // 加载房间信息
    async loadRoom(res) {
        let { content, maskBox } = await this.controllerManager.showDrawerContent({ name: 'onLineGame', tips: `房间号: ${res.roomNumber}`, showCancle: false, sprite_frame: 1206 })
        this.room_content = content
        this.homeElement.createHomeowner(content, res)
        if (res.memberId) {
            this.homeElement.createHomemember(content, res)
        } else {
            this.homeElement.createMemberEmpty(content)
        }
        let is_owner = res.ownerId == userStore().info.id
        this.homeElement.createBottomButton(maskBox, is_owner)
        this.homeElement.createEasterEgg(content)
        res.is_owner = is_owner
        DataManager.Instance.room = res
        // 关闭加入房间的弹框
        if (this.controllerManager.node.getChildByName("joinGame")) {
            this.controllerManager.close('joinGame')
        }
    }
    // 加入房间
    joinGame() {
        if (this.room_number.length != 6) {
            console.log("房间格式不正确")
            showToast("房间格式不正确")
            return
        }
        this.joinGames(this.room_number.join(""))
    }
    joinGames(roomNumber) {
        join({ roomNumber }).then(res => {
            if (this.controllerManager.node.getChildByName("onLineGame")) {
                this.controllerManager.close('onLineGame')
            }
            this.loadRoom(res)
            this.room_number = []
        }).catch(err => {
            showToast(err.message)
            console.log(err)
        })
    }
    confirmLeaveRoom() {
        leave({ roomNumber: DataManager.Instance.room.roomNumber }).then(res => {
            DataManager.Instance.room = null
            this.closeElement()
        }).catch(err => {
            showToast(err.message)
        })
    }
    // 离开房间
    async leaveRoom() {
        this.controllerManager.showMiniLoading({ tips: "确定要离开房间吗?" }).then(res => {
            this.confirmLeaveRoom()
        })
    }
    confirmDissolveRoom() {
        dissolve({ id: DataManager.Instance.room.id }).then(res => {
            DataManager.Instance.room = null
            this.closeElement()
        }).catch((err => {
            showToast(err.message)
            DataManager.Instance.room = null
            this.closeElement()
        }))
    }
    // 解散房间
    dissolveRoom() {
        this.controllerManager.showMiniLoading({ tips: "确定要解散房间吗?" }).then(res => {
            this.confirmDissolveRoom()
        })
    }
    // 邀请好友
    inviteFriends() {
        // wx.shareAppMessage({
        //     title: '这里写分享卡片的标题',
        //     imageUrl: cc.url.raw('img.png'),        // 分享图片要放在 wechatgame/res/raw-assers 路径下
        //     query: 'shareMsg=' + '分享卡片上所带的信息'  // query最大长度(length)为2048
        // });
        showToast("已携带房间号,如果点击分享链接无反应,请手动输入")
        setTimeout(() => {
            userStore().shareAppMessage(`roomNumber=${DataManager.Instance.room.roomNumber}`)
        }, 1000)
    }
    // 下一步
    nextStep() {
        changeLevel({ id: DataManager.Instance.room.id }).then(async res => {
            let { content, maskBox } = await this.controllerManager.showDrawerContent({ name: 'selectLevel', tips: "关卡选择", showCancle: false })
            this.commonElement.createdLevelChange("homeManager", content, res, DataManager.Instance.room, maskBox,)
            this.level_list = res
            this.level_content = content
        }).catch(err => {
            console.log(err.message, "d")
            showToast(err.message)
        })
    }
    // 联机模式开始游戏
    startGame() {
        if (this.level_id == -1) {
            showToast("请先选择关卡")
            return
        }
        let detail = this.level_list.find(item => item.id == this.level_id)
        DataManager.Instance.gameMode = GAME_MODE_ENUM.ONLINE
        console.log(detail)
        this.commonElement.setCreateRecord(detail)
        // DataManager.Instance.mapInfo=
    }
    // 关闭加入房间弹框
    closeJoin() {
        this.room_number = []
        this.controllerManager.close('joinGame')
    }
    // 关闭联机模式弹框
    closeElement() {
        this.room_number = []
        this.controllerManager.close('onLineGame')
        this.homeElement.clearCallBack()
    }
    // 调整准备状态
    updateRoom(event: EventHandler, eventData: string) {
        if (eventData != userStore().info?.id) return
        if (!eventData) return
        let param = {
            id: DataManager.Instance.room?.id,
            ownerReady: 0,
            memberReady: 0,
            type: 0
        }
        if (eventData == DataManager.Instance.room?.ownerId) {
            param.ownerReady = DataManager.Instance.room?.ownerReady == 0 ? 1 : 0
            delete param.memberReady
        } else if (eventData == DataManager.Instance.room?.memberId) {
            param.memberReady = DataManager.Instance.room?.memberReady == 0 ? 1 : 0
            param.type = 1
            delete param.ownerReady
        } else {
            showToast("参数不合法")
            console.log("参数不合法")
            return
        }
        roomChangeReady(param).then(res => {
            let label = event.target.getComponent(Label)
            this.setRoomState(label, param)
            this.loadingRoom = false
        }).catch(err => {
            showToast(err.message)
            console.log(err.message)
            this.loadingRoom = false
        })
    }
    // 调整房间的状态
    setRoomState(label, param) {
        if (param?.ownerReady == 0 || param?.memberReady == 0) {
            label.string = "立即准备"
            label.color = new math.Color(DataManager.Instance.color)
        }
        if (param?.ownerReady == 1 || param?.memberReady == 1) {
            label.string = "取消准备"
            label.color = new math.Color("#999")
        }
        if (param.ownerReady !== undefined) {
            DataManager.Instance.room.ownerReady = param.ownerReady
        }
        if (param.memberReady !== undefined) {
            DataManager.Instance.room.memberReady = param.memberReady
        }
    }
    // 开/关动画
    changeAnimation() {
        let label = this.homeElement.close_node.getComponent(Label)
        if (this.homeElement.can_animation) {
            label.string = "开启动画"
            this.homeElement.can_animation = false
        } else {
            label.string = "关闭动画"
            this.homeElement.can_animation = true
            this.homeElement.playBottomAnimation(this.easterEgg)
        }
    }

    // 关于我们
    async aboutUs() {
        if (DataManager.Instance.drawerNumber != 0) {
            return
        }
        let text = '支持正版游戏:nitrome'
        await this.controllerManager.showDrawerText({ name: 'gameHelp', label: "游戏帮助", text })
    }
    // 退出登录
    logout() {
        if (DataManager.Instance.drawerNumber != 0) {
            return
        }
        this.controllerManager.showMiniLoading({ tips: "确定要退出登录吗?" }).then(res => {
            this.confirmLogout()
        })
        // this.controllerManager.showMiniLoading({
        //     tips: "确定要退出登录吗?",
        //     cancel_text: "再想想",
        //     confirm_target: this.node,
        //     confirm_text: "确定",
        //     confirm_component: "homeManager",
        //     confirm_handler: "confirmLogout"
        // })
    }
    confirmLogout() {
        if (userStore().token == '') {
            director.loadScene('login')
            return
        }
        userStore().logout()
        showToast("操作成功")
    }
    // 试玩关卡
    trialLevels() {
        this.playGame()
    }
    // 开始游戏
    async playGame() {
        if (DataManager.Instance.drawerNumber != 0) {
            return
        }
        let { content } = await this.controllerManager.showDrawerContent({ name: 'gameType', tips: "模式选择" })
        this.commonElement.createPlayGame(content)
    }
    // 选择单/双人
    async selectPerson(event: Event, eventData: string) {
        if (this.loadingLevels) return
        if (eventData == 'doublePerson') {
            if (sys.isMobile) {
                let text = '仅支持pc端小游戏,手机状态下请等待后续联机模式...'
                await this.controllerManager.showDrawerText({ name: 'tips', label: "提示", text })
                return
            }
            this.commonElement.setDoublePersonStatus()
            this.commonElement.setSinglePersonStatus("#fbfbfd", false)
            DataManager.Instance.gameMode = GAME_MODE_ENUM.DOUBLE
        } else if (eventData == 'singlePerson') {
            this.commonElement.setDoublePersonStatus("#fbfbfd", false)
            this.commonElement.setSinglePersonStatus()
            DataManager.Instance.gameMode = GAME_MODE_ENUM.SINGLE
        }
        await this.loadLevels()
    }
    // 游戏帮助
    async gameHelp() {
        if (DataManager.Instance.drawerNumber != 0) {
            return
        }
        let text = '通过控制角色吞吐道具来击晕怪物，\n晕倒状态下的怪物可以被角色吃掉,\n吃掉所有怪物即可通往下一关\n\n1,手机模式下,左半侧屏幕控制角色移动,\n右半侧屏幕控制角色吞/吐道具,\n2,单人电脑模式下,WASD控制角色移动,\n空格键控制角色吞/吐道具\n3,双人电脑模式下,WASD控制绿色角色移动,\n左ctrl控制绿色角色吞/吐道具。\n↑↓←→控制蓝色角色移动,\n空格键控制蓝色角色吞/吐道具\n'
        await this.controllerManager.showDrawerText({ name: 'gameHelp', label: "游戏帮助", text })
    }
    // 加载关卡
    async loadLevels() {
        this.loadingLevels = true
        return getLevels().then(async res => {
            this.level_list = res
            this.loadingLevels = false
            await this.commonElement.selectLevel(this.controllerManager, this.level_list)
        }).catch(res => {
            console.log(res)
        })
    }
    // 确定模式下选择房间
    async avenueLevels(event: Event | null, eventData: string, check: Boolean = true) {
        if (DataManager.Instance.disbledButton) {
            return
        }
        let index = this.level_list.findIndex(item => item.id == eventData)
        if (index == -1) {
            let text = '关卡信息出错,请联系开发人员'
            await this.controllerManager.showDrawerText({ text })
            return
        }
        if (this.level_list[index].levels.length == 0 && check) {
            let text = '当前关卡未解锁,请通关上一关卡后继续'
            await this.controllerManager.showDrawerText({ text })
            DataManager.Instance.disbledButton = true
            return
        }
        if (this.level_id != -1) {
            let label = this.level_content.getChildByName("levelNode").getChildByName(`levelChildren${this.level_id}`).getChildByName("labelNode").getComponent(Label)
            label.color = new math.Color('#999')
        }
        let label = this.level_content.getChildByName("levelNode").getChildByName(`levelChildren${this.level_list[index].id}`).getChildByName("labelNode").getComponent(Label)
        label.color = new math.Color(DataManager.Instance.color)
        this.level_id = this.level_list[index].id
        socket.send(DataManager.Instance.room?.memberId, {
            type: SOCKET_TYPE.CHANGELEVEL,
            roomId: DataManager.Instance.room?.id,
            roomNumber: DataManager.Instance.room?.roomNumber,
            owner: DataManager.Instance.room?.is_owner,
            content: {
                level_id: this.level_id,
                roomId: DataManager.Instance.room?.id,
            }
        })
    }
    // 确定关卡
    async determineLevels(event: Event, eventData: string) {

        if (DataManager.Instance.disbledButton) {
            return
        }
        let index = this.level_list.findIndex(item => item.id == eventData)
        if (index == -1) {
            let text = '关卡信息出错,请联系开发人员'
            await this.controllerManager.showDrawerText({ text })
            return
        }
        if (this.level_list[index].levels.length == 0) {
            let text = '当前关卡未解锁,请通关上一关卡后继续'
            await this.controllerManager.showDrawerText({ text })
            DataManager.Instance.disbledButton = true
            return
        }
        if (this.level_list[index].type == 0) {
            let ad = await this.adManager.playAd()
            if (!ad) return
        }
        DataManager.Instance.audioMgr.stop()
        await this.controllerManager.close('selectLevel')
        // DataManager.Instance.levelIndex = index
        this.commonElement.setCreateRecord(this.level_list[index])
    }
}

